<?php


namespace app\service;


use app\lib\exception\ServiceException;
use app\utils\AliyunOss;
use Symfony\Component\Yaml\Exception\ParseException;
use think\exception\FileException;
use think\File;
use think\Filesystem;
use think\route\dispatch\Callback;

class FilesService
{
    public function uploadFile($file){
        try {
            $path = \think\facade\Filesystem::putFile('', $file);
        } catch (\Exception $exception) {
            throw new ServiceException('文件上传失败');
        }
        return $path;
    }

    private function upload2Oss(String $path, $folder = ''){
        if (strpos($path, env('aliyun.bucketname'))) {
            $path = substr($path,strripos(env('aliyun.bucket'),"/")+1);
        }else {
            $aliyunOss = new AliyunOss();
            $path = config('filesystem.disks.local.root') . DIRECTORY_SEPARATOR . $path;
            try {
                $file = new File($path);
                $path = $aliyunOss->upload($file, $folder);
            }catch (FileException $exception){
                throw new ServiceException($exception->getMessage());
            }
        }

        return $path;
    }

    public function save2Oss(String $paths, $folder = ''){
        if ($paths == '') return null;

        if (strpos($paths, ',')){
            $files = [];
            $paths = explode(',', $paths);
            foreach ($paths as $path){
                $files[] = $this->upload2Oss($path, $folder);
            }
        }else{
            $files = $this->upload2Oss($paths, $folder);
        }

        return $files;
    }
}